import * as http from 'http';
import * as https from 'https';
import * as Router from 'koa-router';
import * as qs from 'querystring';




export default class Http{
    /**
     * 发送消息
     * @param ctx 
     * @param errcode 
     * @param errmsg 
     * @param data 
     */
    static send(ctx: Router.IRouterContext, errcode: number, errmsg?: string, data: ret = {}){
        data.errcode = errcode;
        data.errmsg = errmsg;
        ctx.body = data;
    }

    /**
     * 向指定ip端口的地址发送get请求
     * @param host ip地址
     * @param port 端口号
     * @param path 请求的路由
     * @param data 请求的参数
     * @param safe 是否使用https
     */
    static get(host, port, path, data, safe = false): Promise<ret>{
        return new Promise((resolve, reject) => {
            const content = qs.stringify(data);
            const options:http.RequestOptions = {
                hostname: host,
                path: path + '?' + content,
                method: 'GET',
                port: port,
            };
            let proto: typeof http | typeof https = http;
            if(safe){
                proto = https;
            }

            const req = (<typeof http>proto).request(options, (res) => {
                res.setEncoding('utf8');
                let data = '';
                res.on('data', (chunk) => {
                    data += chunk;
                });
                res.on('end', () => {
                    let data1;
                    try{
                        data1 = JSON.parse(data);
                    }
                    catch(e){
                        console.log('解析数据发生错误', e);
                    }
                    resolve(data1);
                });
            });

            req.on('error', (e) => {
                reject('请求数据发生错误，请求体：' + content + '错误消息:' + e.message);
            });

            req.end();
        });
    }
}


























































declare global {
    interface String {
        format(...args: any[]): string;
    }
}


String.prototype.format = function (...args) {
    let result = <string>this;
    if (args.length > 0) {
        if (args.length == 1 && typeof args[0] == 'object') {
            for (let key in args) {
                if (args[key] != undefined) {
                    let reg = new RegExp('({' + key + '})', 'g');
                    result = result.replace(reg, args[key]);
                }
            }
        }
        else {
            for (let i = 0; i < args.length; i++) {
                if (args[i] != undefined) {
                    let reg = new RegExp('({)' + i + '(})', 'g');
                    result = result.replace(reg, args[i]);
                }
            }
        }
    }
    console.log(result);
    return result;
};